<template>
  <div class="app-container home-dashboard">
    <!-- 欢迎区域 -->
    <el-card class="welcome-card" shadow="never">
      <div class="welcome-content">
        <div class="welcome-info">
          <h2>欢迎回来，{{ userStore.nickName || userStore.name }}！</h2>
          <p class="welcome-time">{{ currentTime }}</p>
        </div>
        <el-avatar :size="60" :src="userStore.avatar" />
      </div>
    </el-card>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6" v-for="stat in statsList" :key="stat.key">
        <el-card class="stat-card" shadow="hover" :class="stat.className">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: stat.color }">
              <el-icon :size="28">
                <component :is="iconMap[stat.icon] || stat.icon" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </div>
          </div>
        </el-card>
          </el-col>
        </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 订单趋势图 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>订单趋势</span>
              <el-radio-group v-model="orderTrendType" size="small" @change="loadOrderTrend">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="orderTrendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 快捷操作 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <div 
              class="quick-action-item" 
              v-for="action in quickActions" 
              :key="action.path"
              @click="handleQuickAction(action.path)"
            >
              <el-icon :size="24" :color="action.color">
                <component :is="iconMap[action.icon] || action.icon" />
              </el-icon>
              <span>{{ action.label }}</span>
            </div>
          </div>
        </el-card>
    </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <!-- 订单状态分布 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <div ref="orderStatusChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 收入趋势图 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>收入趋势</span>
              <el-radio-group v-model="revenueTrendType" size="small" @change="loadRevenueTrend">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="revenueTrendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最新动态 -->
    <el-row :gutter="20">
      <el-col :xs="24">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>最新订单</span>
              <el-button link type="primary" @click="goToOrderRecord">查看全部</el-button>
            </div>
          </template>
          <el-table :data="recentOrders" v-loading="ordersLoading" style="width: 100%">
            <el-table-column label="订单号" min-width="100" align="center"  prop="orderNo"  />
            <el-table-column label="医院名称" min-width="100" align="center"  prop="itemHospitalName" show-overflow-tooltip  />
            <el-table-column label="服务项目" align="center" prop="itemName" show-overflow-tooltip  />
            <el-table-column label="就诊人姓名" align="center" prop="itemPatientName" />
            <el-table-column label="关系" align="center" prop="itemRelation" >
              <template #default="scope">
                <span>{{ getItemRelationText(scope.row.itemRelation) || '--'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="订单总金额" align="center" prop="totalAmount" >
              <template #default="scope">
                <span style="color: #7CBF50;">¥{{ centsToYuan(scope.row.totalAmount) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="订单状态" align="center" prop="orderStatus">
              <template #default="scope">
                <el-tag :type="getOrderStatusTagType(scope.row.orderStatus)">{{ getOrderStatusText(scope.row.orderStatus) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态更新时间" align="center" prop="updateTime" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Home">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import * as echarts from 'echarts'
import { listOrderRecord } from '@/api/orderRecord/orderRecord'
import { getDashboardStats } from '@/api/home/home'
import { centsToYuan } from '@/utils/money'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 当前时间
const currentTime = ref('')
const statsList = ref([])
const orderTrendType = ref('week')
const revenueTrendType = ref('week')
const recentOrders = ref([])
const ordersLoading = ref(false)

// 图表引用
const orderTrendChartRef = ref(null)
const orderStatusChartRef = ref(null)
const revenueTrendChartRef = ref(null)
let orderTrendChart = null
let orderStatusChart = null
let revenueTrendChart = null

// 快捷操作
const quickActions = [
  { label: '订单管理', icon: 'ShoppingCart', path: '/orderRecord', color: '#409EFF' },
  { label: '接单管理', icon: 'List', path: '/attendant/takeOrder', color: '#67C23A' },
  { label: '申请管理', icon: 'Document', path: '/attendant/application', color: '#E6A23C' },
  { label: '提现管理', icon: 'Money', path: '/attendant/withdraw', color: '#F56C6C' },
  { label: '医院管理', icon: 'Hospital', path: '/hospital', color: '#9C27B0' },
  { label: '服务项目管理', icon: 'Files', path: '/item', color: '#00BCD4' },
]

// 图标映射 - 使用Element Plus图标库中实际存在的图标
const iconMap = {
  ShoppingCart: ElementPlusIconsVue.ShoppingCart || ElementPlusIconsVue.ShoppingBag,
  User: ElementPlusIconsVue.User,
  Hospital: ElementPlusIconsVue.OfficeBuilding || ElementPlusIconsVue.House,
  Document: ElementPlusIconsVue.Document || ElementPlusIconsVue.Files,
  Files: ElementPlusIconsVue.Files || ElementPlusIconsVue.Document,
  List: ElementPlusIconsVue.List || ElementPlusIconsVue.Menu,
  Money: ElementPlusIconsVue.Money || ElementPlusIconsVue.Coin,
  Clock: ElementPlusIconsVue.Clock || ElementPlusIconsVue.Timer,
  Checked: ElementPlusIconsVue.Check || ElementPlusIconsVue.CircleCheck,
  Close: ElementPlusIconsVue.Close
}

// 关系映射
const getItemRelationText = (relation) => {
  const relationMap = {
    1: '父母',
    2: '本人',
    3: '子女',
    4: '配偶',
    5: '其他'
  }
  return relationMap[relation] || '--';
}

// 更新当前时间
const updateTime = () => {
  const now = new Date()
  const hours = now.getHours()
  let greeting = '早上好'
  if (hours >= 12 && hours < 18) {
    greeting = '下午好'
  } else if (hours >= 18) {
    greeting = '晚上好'
  }
  currentTime.value = `${greeting}，今天是 ${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`
}

// 加载统计数据
const loadDashboardStats = async () => {
  try {
    const res = await getDashboardStats()
    const data = res.data || {}
    
    statsList.value = [
      {
        key: 'totalOrders',
        label: '总订单数',
        value: data.totalOrderCount || 0,
        icon: 'ShoppingCart',
        color: '#409EFF',
        className: 'stat-card-blue'
      },
      {
        key: 'pendingApplication',
        label: '待处理申请',
        value: data.pendingApplyCount || 0,
        icon: 'Document',
        color: '#67C23A',
        className: 'stat-card-green'
      },
      {
        key: 'attendants',
        label: '陪诊师总数',
        value: data.totalAttendantCount || 0,
        icon: 'User',
        color: '#909399',
        className: 'stat-card-gray'
      },
      {
        key: 'hospitals',
        label: '合作医院',
        value: data.totalHospitalCount || 0,
        icon: 'Hospital',
        color: '#F56C6C',
        className: 'stat-card-red'
      },
      {
        key: 'items',
        label: '服务项目',
        value: data.totalItemCount || 0,
        icon: 'Document',
        color: '#9C27B0',
        className: 'stat-card-purple'
      },
      {
        key: 'pendingWithdraw',
        label: '待处理提现',
        value: data.pendingWithdrawCount || 0,
        icon: 'Money',
        color: '#E6A23C',
        className: 'stat-card-orange'
      }
    ]
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载订单趋势图 - 使用假数据
const loadOrderTrend = async () => {
  if (!orderTrendChartRef.value) return
  
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 200))
  
  // 生成假数据
  const dates = []
  const values = []
  const endDate = new Date()
  const days = orderTrendType.value === 'week' ? 7 : 30
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(endDate)
    date.setDate(date.getDate() - i)
    dates.push(`${date.getMonth() + 1}-${date.getDate()}`)
    // 生成随机订单数（15-35之间）
    values.push(Math.floor(Math.random() * 20) + 15)
  }

  if (!orderTrendChart) {
    orderTrendChart = echarts.init(orderTrendChartRef.value)
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '订单数',
        type: 'line',
        smooth: true,
        data: values,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        },
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }

  orderTrendChart.setOption(option)
}

// 加载订单状态分布 - 使用假数据
const loadOrderStatusDistribution = async () => {
  if (!orderStatusChartRef.value) return

  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 200))
  
  // 假数据
  const data = [
    { value: 45, name: '待支付' },
    { value: 15, name: '待服务' },
    { value: 1180, name: '已完成' },
    { value: 16, name: '已取消' }
  ]

  if (!orderStatusChart) {
    orderStatusChart = echarts.init(orderStatusChartRef.value)
  }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        data: data
      }
    ]
  }

  orderStatusChart.setOption(option)
}

// 加载收入趋势图 - 使用假数据
const loadRevenueTrend = async () => {
  if (!revenueTrendChartRef.value) return

  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 200))
  
  // 生成假数据
  const dates = []
  const values = []
  const endDate = new Date()
  const days = revenueTrendType.value === 'week' ? 7 : 30
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(endDate)
    date.setDate(date.getDate() - i)
    dates.push(`${date.getMonth() + 1}-${date.getDate()}`)
    // 生成随机收入（300-800之间，单位：分）
    const revenue = Math.floor(Math.random() * 500) + 300
    values.push(centsToYuan(revenue * 100)) // 转换为元
  }

  if (!revenueTrendChart) {
    revenueTrendChart = echarts.init(revenueTrendChartRef.value)
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        return `${params[0].name}<br/>收入: ¥${params[0].value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        data: values,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#67C23A' },
            { offset: 1, color: '#85CE61' }
          ])
        }
      }
    ]
  }

  revenueTrendChart.setOption(option)
}

// 加载最新订单
const loadRecentOrders = async () => {
  ordersLoading.value = true
  
  // 获取最新的10条订单数据
  await listOrderRecord({ pageNum: 1, pageSize: 10 }).then(res => {
    recentOrders.value = res.rows
  }).finally(() => {
    ordersLoading.value = false
  })
}

// 订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '待服务',
    2: '已完成',
    3: '已取消'
  }
  return statusMap[status] || '--'
}

// 订单状态标签类型
const getOrderStatusTagType = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'danger'
  }
  return statusMap[status] || 'info'
}

// 快捷操作
const handleQuickAction = (path) => {
  router.push(path)
}

// 查看订单详情
const viewOrderDetail = (row) => {
  router.push({
    path: '/orderRecord',
    query: { id: row.id }
  })
}

// 跳转到订单记录
const goToOrderRecord = () => {
  router.push('/orderRecord')
}

// 窗口大小改变时重新调整图表
const handleResize = () => {
  orderTrendChart?.resize()
  orderStatusChart?.resize()
  revenueTrendChart?.resize()
}

onMounted(() => {
  updateTime()
  loadDashboardStats()
  loadRecentOrders()
  
  nextTick(() => {
    loadOrderTrend()
    loadOrderStatusDistribution()
    loadRevenueTrend()
  })

  window.addEventListener('resize', handleResize)
  
  // 每分钟更新时间
  const timeInterval = setInterval(updateTime, 60000)
  
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    clearInterval(timeInterval)
    orderTrendChart?.dispose()
    orderStatusChart?.dispose()
    revenueTrendChart?.dispose()
  })
})
</script>

<style scoped lang="scss">
.home-dashboard {
  .welcome-card {
    margin-bottom: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    
    :deep(.el-card__body) {
      padding: 24px;
    }
    
    .welcome-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: white;
      
      .welcome-info {
        h2 {
          margin: 0 0 8px 0;
          font-size: 24px;
          font-weight: 500;
          color: white;
        }
        
        .welcome-time {
    margin: 0;
          font-size: 14px;
          opacity: 0.9;
        }
      }
    }
  }

  .stats-row {
    margin-bottom: 20px;
    
    .stat-card {
      height: 100%;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-5px);
      }
      
      :deep(.el-card__body) {
        padding: 20px;
      }
      
      .stat-content {
        display: flex;
        align-items: center;
        gap: 16px;
        
        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
        }
        
        .stat-info {
          flex: 1;
          
          .stat-value {
            font-size: 28px;
            font-weight: 600;
            color: #303133;
            margin-bottom: 4px;
          }
          
          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .charts-row {
    margin-bottom: 20px;
    
    .chart-card {
      height: 100%;
      
      :deep(.el-card__header) {
        padding: 16px 20px;
        border-bottom: 1px solid #EBEEF5;
      }
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 500;
      }
      
      .chart-container {
        width: 100%;
        height: 300px;
      }
    }
  }

  .quick-actions {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    
    .quick-action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 24px;
      border: 1px solid #EBEEF5;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        border-color: #409EFF;
        background-color: #F5F7FA;
        transform: translateY(-2px);
      }
      
      .el-icon {
        margin-bottom: 8px;
      }
      
      span {
        font-size: 14px;
        color: #606266;
      }
    }
  }
}

@media (max-width: 768px) {
  .home-dashboard {
    .stats-row {
      .stat-card {
        margin-bottom: 16px;
      }
    }
    
    .quick-actions {
      grid-template-columns: 1fr;
    }
  }
}
</style>
